import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationsStore with ChangeNotifier, DiagnosticableTreeMixin {

  late final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin;
  Function? _messageCallBack;

  // 消息初始化
  void init() async {
    _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

    // android初始化
    var initializationSettingsAndroid = const AndroidInitializationSettings('@mipmap/ic_launcher');

    // iOS 初始化设置
    var initializationSettingsIOS = const DarwinInitializationSettings(
      requestSoundPermission: true,
      requestBadgePermission: true,
      requestAlertPermission: true,
    );

    var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );

    await _flutterLocalNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse response) {
      _onDidReceiveNotificationResponse(response);
    });

    await _flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(alert: true, badge: true, sound: true);
  }

  // 监听用户
  Future<void> _onDidReceiveNotificationResponse(NotificationResponse response) async {
    final payload = response.payload;
    if (payload == null) {
      debugPrint('通知无有效载荷！！！');
    } else {
      debugPrint('用户点击了消息！！！！-----------$payload');
      if (_messageCallBack is Function) {
        _messageCallBack!(payload);
      }
      // controller.runJavaScript("window.dispatchEvent(new CustomEvent('notificationResponse', { detail: JSON.parse('$payload') }))");
    }
  }

  void changeMessageFun(Function? callBack) {
    _messageCallBack = callBack;
  }

  // 发送消息
  void sendMessage(id, String title, String content, payload) async {
    String payloadString = jsonEncode(payload);
    const AndroidNotificationDetails androidDetails =
    AndroidNotificationDetails(
      'notification_channel_updates',
      '更新通知',
      channelDescription: '用于更新的通知',
      importance: Importance.max,
      priority: Priority.high
    );

    const DarwinNotificationDetails iosDetails = DarwinNotificationDetails(
      presentAlert: true,
      presentBadge: true,
      presentSound: true,
    );

    const NotificationDetails details = NotificationDetails(android: androidDetails, iOS: iosDetails);

    await _flutterLocalNotificationsPlugin.show(id, title, content, details, payload: payloadString);
  }

}

